<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="app-container">
          <el-row>
            <el-col :span="8"><span class="el-custom-title">工艺要求</span> </el-col>
            <el-col :span="16" style="float:right;">
              <el-button-group style="float: right">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  class="el-button--mini"
                  @click="handleCreate"
                  v-if='this.temp.id == 0'
                  >添加</el-button
                >
                <el-button type="primary" size="mini"
                 icon="el-icon-edit"
                 @click="handleUpdate()"  v-if='this.temp.id != 0'>
                  编辑
                </el-button>
                <el-button
                  size="mini"
                   icon="el-icon-delete"
                  type="danger"
                  @click="ui_delete2()"
                  v-if='this.temp.id != 0'
                >
                  删除
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>
          <el-row type="flex" justify="start">
            <span>{{ this.temp.sopRequirements }}</span>
          </el-row>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="app-container">
          <el-row
            ><el-upload
              ref='upload'
              class="upload-demo"
              action="http://localhost:8081/mes/mESTechnologySOP/upload"
              :on-preview="handlePreview"
              :on-remove="ui_delete"
              :file-list="this.lstFiles"
              list-type="picture"
              :http-request="uploadImage"
              :before-upload="beforeAvatarUpload"
            >
              <el-button size="mini" type="primary" icon="el-icon-upload">上传指导书</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible" append-to-body>
  <img width="100%" fit="contain" :src="dialogImageUrl" alt="">
</el-dialog>
            </el-row
          >
        </div>
      </el-col>
    </el-row>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="technologyId" prop="technologyId" v-if="false">
          <el-input v-model="temp.technologyId" />
        </el-form-item>
         <el-form-item label="标准工艺" prop="">
          <span>{{this.technology != null? this.technology.technologyName:''}}</span>
        </el-form-item>
        <el-form-item label="工艺要求" prop="sopRequirements">
          <el-input v-model="temp.sopRequirements" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? ui_create() : ui_update()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <router-view></router-view>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import request from "@/utils/request";
import {
  getAll,
  getOne,
  getList,
  create,
  update,
  deleteBatch,
  upload,
  deletePicture
} from "@/api/mesTechnologySOP";

export default {
  name: "mestechnologysoplist",
  components: { Pagination },
  data() {
    return {
      filterText: "",
      data2: [],
      defaultProps: {
        children: "children",
        label: "MESTechnologySOP"
      },
      list: null,
      list2: null,
      listLoading: true,
      total: 0,
      total2: 0,
      listQuery: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      listQuery2: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      currentMESTechnologySOPId: 0,
      curMESTechnology:
      {
         curId:0,
         curName:''
      },
      dialogFormVisible: false,
      dialogVisible:false,
      dialogImageUrl:'',
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建"
      },
      rules: {
        technologyId: [
          {
            required: true,
            message: "请先选择一个工艺",
            trigger: "change"
          }
        ],
        sopRequirements: [
          {
            required: true,
            message: "工艺要求不能为空！",
            trigger: "change"
          }
        ],
      },
      temp: {
        id: 0,
        technologyId: this.technology == null? 0: this.technology.id,
        sopRequirements: "",
        attachmentFiles: ""
      },
      //附件图片
      lstFiles: [],
    }
  },
  props: {
      technology: {}
  }
  ,
  watch: {
     technology:function(newValue,oldValue)
     {
        if(newValue != null)
        {
        this.technology = newValue
        this.temp.technologyId = newValue.id
        this.fetchData()
        }
     },
     deep:true
  },
  created() {
    this.fetchData();
  },
  methods: {
    handleSelectionChange(val) {
      this.lstSelected = val;
    },
    fetchData() {
      if(this.technology == null) return
      this.listLoading = true;
      let params = {
        technologyId: this.technology.id
      };
      getOne(params).then(response => {
        this.resetTemp()
        this.lstFiles.length = 0
        this.$refs["upload"].clearFiles()
        this.temp = response.data;
        if (this.temp != null) {
          if (
            this.temp.attachmentFiles != null &&
            this.temp.attachmentFiles.length > 0
          ) {
              this.temp.attachmentFiles.split(";").forEach(itm => {
              if (itm.trim().length > 0) {
                this.lstFiles.push({ name: "", url: itm.trim() });
              }
            });
          }
        }
        else
        {
           this.resetTemp()
        }
        this.listLoading = false;
      });
    },

    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    ui_create() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.temp.id = 0; //自增
          
          create(this.temp).then((response) => {
            this.temp = response.data
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_update() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          update(this.temp).then(() => {
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_delete(file, fileList) {
      ;
      if (file == null) {
        this.$message.error("请先选择要删除的标准指导书");
        return;
      }
      let ids = [];
      ids.push(this.temp.id);
      ids.push(file.url);
      deletePicture(ids).then(() => {
        const index = this.lstFiles.findIndex(v => v.url === file.url);
        this.lstFiles.splice(index, 1);

        this.dialogFormVisible = false;
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000
        });
      });
    },
     ui_delete2() {
      let ids = [];
      ids.push(this.temp.id);
      deleteBatch(ids).then(() => {
        this.temp.resetTemp()
        this.lstFiles.length = 0
        this.$refs["upload"].clearFiles()
        this.dialogFormVisible = false;
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000
        });
      });
    },
    resetTemp() {
      this.temp = {
        id: 0,
        technologyId: this.technology == null? 0: this.technology.id,
        sopRequirements: "",
        attachmentFiles: ""
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdate() {
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 上传图片方法
    uploadImage(param) {
      const formData = new FormData();
      formData.append("file", param.file);
      formData.append("id", this.temp.id);
      ;
      upload(formData)
        .then(response => {
          console.log("上传图片成功");
          //可以在前端设置普片全路径
          //this.form.picUrl = process.env.VUE_APP_BASE_API + response.imgUrl
          this.lstFiles.push({name:'',url:response.data})
        })
        .catch(response => {
          console.log(response.data);
        });
    },
    // 资质照片上传前校验
    beforeAvatarUpload(file) {
      const isPic = file.type.indexOf("image") >= 0;
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isPic) {
        this.$message.error("指导书照片只能为图片格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      if (this.lstFiles.length > 4) {
        this.$message.error("上传图片数量不能超过4个");
      }
      return isPic && isLt2M && this.lstFiles.length <= 4;
    }
  }
};
</script>
<style>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
